package com.zdya.combatdocuments.component;

import cn.hutool.core.io.FileUtil;
import com.zdya.combatdocuments.constant.Constants;
import com.zdya.combatdocuments.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;


/**
 * * @author: bj
 * * @date: 2023/6/7
 * * @desc: 文件操作工具
 */
@Slf4j
@Component
public class DocumentUtils {

    /**
     * @param multipartFile 文件
     */
    public String storageFile(MultipartFile multipartFile, Integer fileType, String uuId) {
        // 存储文件到本地
        String originalFilename = multipartFile.getOriginalFilename();
        String rootFilePath = "";
        // 图片
        if (fileType.equals(Constants.msg_type_2)) {
            String profilePath = CombatDocumentConfig.getProfile() + File.separator+Constants.PIC_PREFIX_PATH;
            File file = new File(profilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            rootFilePath = profilePath + File.separator + uuId + "_" + originalFilename;
        }
        // 普通文件
        if (fileType.equals(Constants.msg_type_3)) {
            String profilePath = CombatDocumentConfig.getProfile() + File.separator + Constants.FILE_PREFIX_PATH;
            File file = new File(profilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            rootFilePath = profilePath + File.separator+ uuId + "_" + originalFilename;
        }
        // 文书
        if (fileType.equals(Constants.msg_type_4)) {
            String profilePath = CombatDocumentConfig.getProfile() + File.separator+ Constants.DOC_PREFIX_PATH;
            File file = new File(profilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            rootFilePath = profilePath + File.separator+ uuId + ".pdf";
        }
        try {
            multipartFile.transferTo(new File(rootFilePath)); //把文件写入到上传的路径; //获取上传的路径
//            FileUtil.writeBytes(multipartFile.getBytes(), rootFilePath);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("文件发送失败！");
        }
        return rootFilePath;
    }

}
